package poker;

import java.util.ArrayList;

import exception.HandSizeEx;

public class Bot extends Player {

	public Bot(String name, int tokens) {
		hand = new ArrayList<Card>(5);
		this.name = name;
		this.tokens = tokens;
		bet = 0;
		hasFolded = false;
		allIn = false;
		disconnected = false;
		wins = 0;
	}

	@Override
	public PlayerAction takeTurn(Phase phase, int bet, boolean allIn) throws HandSizeEx {
		if(phase == Phase.Exchange) {
			if (hand.size() < 5) {
				throw new HandSizeEx();
			}
	
			int result[] = new int[6];
			int cards[] = new int[5];
			for (int i = 0; i < 5; i++) {
				cards[i] = hand.get(i).getCard();
			}
			try {
				Table.analyzeCards(result, cards);
			} catch (Exception e) {
				//NIEMOŻLIWE//
				return PlayerAction.FOLD;
			}
			if (result[0] == 4) {
				for (int i = 4; i > -1; i--) {
					if ((hand.get(i).getCard()) % 13 != result[1]) {
						hand.remove(i);
					}
				}
				return PlayerAction.FOLD;
			}
			if (result[0] == 2) {
				for (int i = 4; i > -1; i--) {
					if ((hand.get(i).getCard()) % 13 != result[1]) {
						hand.remove(i);
					}
				}
				return PlayerAction.FOLD;
			}
			if (result[0] != 1) {
				return PlayerAction.FOLD;
			}
	
			int score[] = new int[5];
			int buffer = 0;
	
			for (int i = 0; i < 5; i++) {
				buffer = cards[i];
				for (int j = 0; j < 13; j++) {
					cards[i] = j;
					try {
						Table.analyzeCards(result, cards);
					} catch (Exception e) {
						//NIEMOŻLIWE//
						return  PlayerAction.FOLD;
					}
					if (result[0] != 6) {
						score[i] += result[0];
					}
				}
	
				for (int j = 0; j < 4; j++) {
					cards[i] = j * 13;
					try {
						Table.analyzeCards(result, cards);
					} catch (Exception e) {
						//NIEMOŻLIWE//
						return PlayerAction.FOLD;
					}
					if (result[0] == 6) {
						score[i] += result[0];
					}
				}
	
				cards[i] = buffer;
			}
	
			buffer = 0;
			for (int i = 0; i < 5; i++) {
				if (score[i] >= score[buffer]) {
					buffer = i;
				}
			}
			if (score[buffer] > 5) {
				hand.remove(buffer);
			} else {
				for (int i = 3; i > -1; i--) {
					hand.remove(i);
				}
			}
		} else {
			if(bet > tokens) {
				fold();
				return PlayerAction.FOLD;
			} else if(allIn) {
				bet = tokens;
				allIn();
				return PlayerAction.ALLIN;
			} else if(bet == 0) {
				return PlayerAction.BET;
			} else {
				this.bet = bet;
				return PlayerAction.CALL;
			}
		}
		return PlayerAction.FOLD;
	}

	@Override
	public void endTurn() throws HandSizeEx {
	}

	@Override
	public void printCards(int i) throws HandSizeEx {
		System.out.println("Gracz " + i);
		if (hand.size() != 5)
			throw new HandSizeEx();
		for (int j = 0; j < 5; j++) {
			System.out.println("  " + hand.get(j).getCardTxt());
		}
		System.out.println();
	}
	
	@Override
	public boolean isBot() {
		return true;
	}

	@Override
	public void exchangeCards(int cards[]) {}
}
